package com.gae101;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class ProfileServlet extends HttpServlet {

	private static final long serialVersionUID = 6900552341132577222L;
	
	private static final Logger log = Logger.getLogger(ProfileServlet.class.getName());
	
	private static final String KIND = "UserDevice";

	boolean checkStatus(String value) {
		if (value == null) return false;
		if (value.equals("-")) return false;
		if (!(value.equals("ON") || value.equals("OFF"))) return false;
		return true;
	}
	boolean checkType(String value) {
		log.info("checkType : " + value);
		if (value == null) return false;
		if (value.equals("-")) return false;
		if (!(value.equals("VIEWER") || value.equals("TAKER"))) return false;
		return true;
	}
	
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		if (user == null) {
			return;
		}
		
		String cmd = req.getParameter("cmd");
		String id = req.getParameter("id");
		String status = req.getParameter("status");
		String type = req.getParameter("type");
		
		if (!cmd.equals("change")) return;
		
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		
		System.out.println(id);
		Key key = new KeyFactory.Builder(KIND, Long.parseLong(id)).getKey();
		Query query = new Query(KIND).setFilter(new FilterPredicate(Entity.KEY_RESERVED_PROPERTY, Query.FilterOperator.EQUAL, key));
		Entity device = datastore.prepare(query).asSingleEntity();
		
		System.out.println(device);
		if (device == null) return;
		
		device.setProperty("type", type);
		device.setProperty("status", status);
		
		datastore.put(device);

		String ret = new StringBuilder().append(type).append(":").append(status).toString();
		res.getOutputStream().write(ret.getBytes());
	}
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		String loginUrl = userService.createLoginURL(req.getRequestURI());
		req.setAttribute("loginUrl", loginUrl);

		if (user == null) {
			resp.sendRedirect(loginUrl);
			return;
		}
		
		String userId = user.getUserId();
		
		req.setAttribute("nickname", user.getNickname());
		req.setAttribute("logoutUrl", userService.createLogoutURL(req.getRequestURI()));

		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		
		Filter userFilter = new FilterPredicate("userId", FilterOperator.EQUAL, userId);
		
		Query query = new Query(KIND).setFilter(userFilter);
		List<Entity> devices = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(15));
		
		req.setAttribute("devices", devices);
		log.info("devices : size " + devices.size());
		req.getRequestDispatcher("profile.jsp").forward(req, resp);
	}

}
